import React from 'react';
import { BrowserRouter } from 'react-router-dom';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import App from './app';
import configureStore from './store';
import rootSaga from './sagas';
import './styles/index.less';

// if ('serviceWorker' in navigator) {
//   window.addEventListener('load', () => {
//     navigator.serviceWorker.register('/service-worker.js').then((registration) => {
//       console.log('SW registered: ', registration)
//     }).catch((registrationError) => {
//       console.log('SW registration failed: ', registrationError)
//     })
//   })
// }

const renderDOM = () => {
  const root = document.querySelector('#root');

  const { pathname, host } = window.location;
  // 缓存的key
  const localStorageKey = `W_${host}_${pathname.replace(/\/*/g, '')}`;
  // 缓存的value
  const localStorageValue = JSON.parse(localStorage.getItem(localStorageKey)) || undefined;

  // 用户信息发生改变时 清空缓存
  // if (
  //   localStorageValue
  //   && localStorageValue.user
  //   && localStorageValue.user.userId != sessionStorage.getItem('userId')
  // ) {
  //   localStorage.removeItem(localStorageKey);
  //   localStorageValue = undefined;
  // }

  // 创建store 以及运行saga等中间件
  const store = configureStore(localStorageValue);
  store.runSaga(rootSaga);

  // 监听dispatch事件
  store.subscribe(() => {
    const state = store.getState();
    try {
      localStorage.setItem(localStorageKey, JSON.stringify(state)); // 实时保存缓存数据
    } catch (e) {
      localStorage.clear();
    }
  });

  window.store = store;

  const Application = (
    <Provider store={store}>
      <BrowserRouter>
        <App />
      </BrowserRouter>
    </Provider>
  );
  render(Application, root);
};


renderDOM();
